#!/usr/bin/env node

import { McpServer, ResourceTemplate } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";

// 模拟天气数据
const weatherData = {
  "北京": {
    temperature: 20,
    condition: "晴朗",
    humidity: 45,
    windSpeed: 12
  },
  "上海": {
    temperature: 23,
    condition: "多云",
    humidity: 60,
    windSpeed: 15
  },
  "广州": {
    temperature: 28,
    condition: "小雨",
    humidity: 75,
    windSpeed: 8
  }
};

// 创建 MCP 服务器
const server = new McpServer({
  name: "WeatherServer",
  version: "1.0.0",
  description: "一个简单的天气信息服务器"
});

// 添加天气资源
server.resource(
  "weather",
  new ResourceTemplate("weather://{city}", { list: undefined }),
  async (uri, { city }) => {
    const cityData = weatherData[city as keyof typeof weatherData];
    
    if (!cityData) {
      return {
        contents: [{
          uri: uri.href,
          text: `抱歉，未找到 ${city} 的天气信息。`
        }]
      };
    }

    return {
      contents: [{
        uri: uri.href,
        text: `${city}的天气情况：
温度: ${cityData.temperature}°C
天气: ${cityData.condition}
湿度: ${cityData.humidity}%
风速: ${cityData.windSpeed}km/h`
      }]
    };
  }
);

// 添加获取天气的工具
server.tool(
  "get_weather",
  "获取指定城市的天气信息",
  { city: z.string() },
  async ({ city }) => {
    const cityData = weatherData[city as keyof typeof weatherData];

    if (!cityData) {
      return {
        content: [{ 
          type: "text", 
          text: `抱歉，未找到 ${city} 的天气信息。` 
        }],
        isError: true
      };
    }

    return {
      content: [{
        type: "text",
        text: `${city}的天气情况：
温度: ${cityData.temperature}°C
天气: ${cityData.condition}
湿度: ${cityData.humidity}%
风速: ${cityData.windSpeed}km/h`
      }]
    };
  }
);

// 添加天气提示模板
server.prompt(
  "weather_query",
  { city: z.string() },
  ({ city }) => ({
    messages: [{
      role: "user",
      content: {
        type: "text",
        text: `请告诉我${city}的天气情况。请包含温度、天气状况、湿度和风速等信息。`
      }
    }]
  })
);



// 启动服务器
async function main() {
  const transport = new StdioServerTransport();
  await server.connect(transport);
  console.log("天气服务器已启动...");
}

main().catch(error => {
  console.error("服务器启动失败:", error);
});
